# coding:utf-8
# Author : hiicy redldw
# Date : 2019/03/29

from numpy import *

# 断点：F7:一步一步往下，会进入函数块
#       shift F7 跳出函数块
class Newdata:#描述符
    def __init__(self, value):
        self.value = value

	def __get__(self, instance, owner):
		print('print get')
		return self.value

	def __set__(self, instance, value):
		pass


# 创建FP树的数据结构
class treeNode:
	def __init__(self, nameValue, numOccur, parentNode):
		self.name = nameValue
		self.count = numOccur  # 出现的次数计数
		self.nodeLink = None  # 链接相似的元素项
		self.parent = parentNode
		self.children = {}

	def inc(self, numOccur):
		self.count += numOccur

    def disp(self, ind=1): # REW:利用缩进来控制显示，当初的多级评论也是如此
        print(' ' * ind, self.name, ' ', self.count) # 每个缩进表示所处的树的深度
        for child in self.children.values():
            child.disp(ind + 1)

def createTree(dataSet,minSup=1):
    headerTable:dict={}
    for trans in dataSet: # 统计各元素项频率
        for item in trans:
            headerTable[item] = headerTable.get(item,0) + dataSet[trans]
    for k in list(headerTable.keys()): # 移除不满足最小支持度的元素项
        if headerTable[k] < minSup:
            del headerTable[k]

    freqItemSet = set(headerTable.keys())
    if len(freqItemSet) == 0:return None,None
    for k in headerTable:
        headerTable[k] = [headerTable[k],None]
    retTree = treeNode('Null Set', 1, None)
    for transSet,count in dataSet.items():
        localD = {}
        for item in transSet:
            if item in freqItemSet:
                localD[item] = headerTable[item][0]
        if len(localD) > 0:  # 根据全局频率对每个事物中元素进行排序
            orderedItems = [v[0] for v in sorted(localD.items(),key=lambda p:p[1],reverse=True)]
            # 使用排序后频率项对树进行填充
            updateTree(orderedItems,retTree,headerTable,count)
    return retTree,headerTable

def updateTree(items,inTree,headerTable,count):
    if items[0] in inTree.children:
        inTree.children[items[0]].inc(count)
    else:
        #不在，就构造节点
        inTree.children[items[0]]=treeNode(items[0],count,inTree)
        if headerTable[items[0]][1] == None:
            # 更新头指针表 它指向给定类型的第一个实例
            headerTable[items[0]][1] = inTree.children[items[0]]
        else:
            updateHeader(headerTable[items[0]][1],inTree.children[items[0]])
    if len(items)>1:
        updateTree(items[1::],inTree.children[items[0]],headerTable,count)
def updateHeader(nodeToTest:treeNode,targetNode):
    # 更新、链接相似项；确保节点链接指向树中该元素项的每一个实例
    while nodeToTest.nodeLink != None:
        nodeToTest = nodeToTest.nodeLink
    nodeToTest.nodeLink = targetNode


def loadSimpDat():
    simpDat = [['r', 'z', 'h', 'j', 'p'],
               ['z', 'y', 'x', 'w', 'v', 'u', 't', 's'],
               ['z'],
               ['r', 'x', 'n', 'o', 's'],
               ['y', 'r', 'x', 'z', 'q', 't', 'p'],
               ['y', 'z', 'x', 'e', 'q', 's', 't', 'm']]
    return simpDat

def createInitSet(dataSet):
    retDict = {}
    for trans in dataSet:
        retDict[frozenset(trans)] = 1
    return retDict

def ascendTree(leafNode,prefixPath):
    if leafNode.parent != None:
        prefixPath.append(leafNode.name)
        ascendTree(leafNode.parent,prefixPath) # 迭代上溯整棵树


def findPrefixPath(basePat,treeNode):
    condPats = {}
    while treeNode != None:
        prefixPath = []
        ascendTree(treeNode,prefixPath)
        if len(prefixPath) > 1:
            condPats[frozenset(prefixPath[1:])] = treeNode.count # 根据起始项的count
        treeNode = treeNode.nodeLink  # 寻找相似项
    return condPats

def mineTree(inTree,headerTable,minSup,preFix,freqItemList):
    bigL = [v[0] for v in sorted(headerTable.items(),key=lambda p:p[1][0])]
    for basePat in bigL:
        newFreqSet = preFix.copy()
        newFreqSet.add(basePat)
        freqItemList.append(newFreqSet)
        condPattBases = findPrefixPath(basePat,headerTable[basePat][1])
        myCondTree,myHead = createTree(condPattBases,minSup)#从条件模式基构建条件FP树
        if myHead != None:
            mineTree(myCondTree,myHead,minSup,newFreqSet,freqItemList)


# initSet = createInitSet(loadSimpDat())
# print(initSet)
# myFptree,myHeaderTab = createTree(initSet,3)
# freqItems = []
# mineTree(myFptree,myHeaderTab,3,set([]),freqItems)
# print(freqItems)


import re
def textParse(bigString):
    urlsRemoved = re.sub('(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*', '', bigString)
    listOfTokens = re.split(r'\W*', urlsRemoved)
    return [tok.lower() for tok in listOfTokens if len(tok) > 2]

def mineTweets(tweetArr, minSup=5):
    parsedList = []
    for i in range(14):
        for j in range(100):
            parsedList.append(textParse(tweetArr[i][j].text))
    initSet = createInitSet(parsedList)
    myFPtree, myHeaderTab = createTree(initSet, minSup)
    myFreqList = []
    mineTree(myFPtree, myHeaderTab, minSup, set([]), myFreqList)
    return myFreqList
parsedDat = [line.split() for line in open(r'F:\Resources\Dataset\kosarak.dat').readlines()]
print('sf')
initSet = createInitSet(parsedDat)
myFPtree,myHeaderTab = createTree(initSet,100000)
myFreqList = []
mineTree(myFPtree,myHeaderTab,100000,set([]),myFreqList)
print(myFreqList)
